package com.wfg.nettydemo.io.nio.channel;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @author wufagang
 * @description telnet 127.0.0.1 7000 命令写入数据测试
 * @date 2022年05月28日 15:34
 * scattering: 将数据写入到buffer时，可以采用buffer 数组数组，依次写入
 * gathering： 从buffer 读取数据时，可以采用buffer 数组数组，依次读取
 */
public class ScatteringAndGatheringTest {
    public static void main(String[] args) throws Exception{
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress address = new InetSocketAddress(7000);
        //绑定端口到 socket 并启动
        serverSocketChannel.socket().bind(address);
        ByteBuffer[] buffers = new ByteBuffer[2];
        buffers[0] = ByteBuffer.allocate(5);
        buffers[1] = ByteBuffer.allocate(3);

        SocketChannel socketChannel = serverSocketChannel.accept();

        int messageLength = 8;
        while (true){
            int byteRead = 0;
            while (byteRead < messageLength){
                long l = socketChannel.read(buffers);
                byteRead += l;
                System.out.println("byteRead = "+byteRead);
                Arrays.asList(buffers).stream().map(buffer->
                    "position = " + buffer.position() + "limit = "+ buffer.limit()
                ).forEach(System.out::println);
            }
            //将所有的 buffer 进行 flip
            Arrays.asList(buffers).forEach(buffer -> buffer.flip());
            long byteWirte = 0;
            while (byteWirte < messageLength){
                long write = socketChannel.write(buffers);
                byteWirte += write;
            }
            Arrays.asList(buffers).forEach(item->item.clear());
            System.out.println("byteRead = "+ byteRead +"bytewrite = "+byteWirte+",messagelength = "+messageLength);
        }

    }
}
